// components/showView/signUp/weiActivityCanvas.js
Component({
  /**
   * 开启全局样式
   * **/
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的初始数据
   * canvas组件传递数据
   */
  data: {
    wei_canvas_data: {
      top_bg: "",
      title: "标题",
      qrcode: "",
      shop_name: "",
      salary: '',
      position: ''
    },
    canvas_src: ""
  },
  /**
   * 组件的属性列表
   */
  properties: {
    /**
     * 微报名canvas组件属性
     * 接收page参数
     * **/
    weiActivityCanvas: {
      type: Object,
      value: '',
      observer: function (newVal, oldVal) {
        let that = this;
        that.setData({
          top_bg: newVal.top_bg,
          title: newVal.title,
          qrcode: newVal.qrcode,
          position: newVal.position,
          salary: newVal.salary,
          shop_name: '招聘职位'
        })
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 点击保存canvas
     * **/
    saveCanvasImg: function () {
      this.saveImgFun()
    },
    //长按保存
    longTap: function () {
      let that = this;
      wx.showActionSheet({
        itemList: ['保存图片'],
        itemColor: "#333333",
        success: function (res) {
          that.saveImgFun()
        }
      })
    },

    //封装保存图片函数
    saveImgFun() {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            //请求授权
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success(res) {
                //用户调用成功之后，后续再调用不会出现弹框
                // wx.startRecord()
                //通过缓存获取生成的图片路径
                wx.getStorage({
                  key: 'canvasImg',
                  success: function (res) {
                    //获取图片信息
                    wx.getImageInfo({
                      src: res.data,
                      success: function (ret) {
                        var path = ret.path;
                        //保存图片
                        wx.saveImageToPhotosAlbum({
                          filePath: path,
                          success(result) { }
                        })
                      }
                    })
                  }
                })
              },
              fail(res) {
                wx.showToast({
                  title: '您已拒绝授权',
                  icon: 'none'
                })
              }
            })
          } else {
            wx.getStorage({
              key: 'canvasImg',
              success: function (res) {
                //获取图片信息
                wx.getImageInfo({
                  src: res.data,
                  success: function (ret) {
                    var path = ret.path;
                    wx.saveImageToPhotosAlbum({
                      filePath: path,
                      success(result) { }
                    })
                  }
                })
              }
            })
          }
        }
      })
    }

  },

  /**
  * 组件所在页面的生命周期函数
  * **/
  pageLifetimes: {
    show: function () {
      let that = this;
      console.log(that.data.title)
      let screen_width = wx.getSystemInfoSync().screenWidth;
      let scale = screen_width / 750;
      //首先创建一个canvas绘图，有一些绘图方法
      const ctx = wx.createCanvasContext('activityCanvas', this)
      //先绘制背景色
      ctx.setLineWidth(1)
      drawRoundRect(ctx, 0, 0, 670 * scale, 756 * scale, 8 * scale)
      ctx.setFillStyle('#ffffff')
      ctx.fill()

      //绘制上半部分图片
      ctx.drawImage(that.data.top_bg, 20 * scale, 20 * scale, 630 * scale, 360 * scale)

      //标题
      ctx.setFontSize(32 * scale)
      ctx.setFillStyle("#333333")
      drawStrWithAlignCenter(ctx, that.data.title, 20 * scale, 442 * scale, 630 * scale, 360 * scale, 20, scale)

      // //绘制二维码图片
      console.log('--------------qrcode---------------')
      console.log(that.data.qrcode)
      ctx.drawImage(that.data.qrcode, 30 * scale, 494 * scale, 220 * scale, 220 * scale)
      console.log(that.data.qrcode)

      //招聘职位
      ctx.setFontSize(32 * scale)
      ctx.setFillStyle("#333333")
      ctx.fillText(that.data.shop_name, 300 * scale, 520 * scale);
      
      ctx.setFontSize(28 * scale)
      ctx.setFillStyle("#333333")
      ctx.fillText(that.data.position, 300 * scale, 570 * scale);

      //薪水
      ctx.setFontSize(28 * scale)
      ctx.setFillStyle("#FF6666")
      ctx.fillText(that.data.salary, 300 * scale, 610 * scale);

      //识别二维码背景色
      ctx.setFillStyle('#F9B12F')
      ctx.fillRect(300 * scale, 650 * scale, 304 * scale, 48 * scale)

      //识别二维码
      ctx.setFontSize(24 * scale)
      ctx.setFillStyle("#ffffff")
      ctx.fillText("识别二维码了解招聘详情", 320 * scale, 684 * scale);

      

      //先加载再执行绘制
      ctx.draw()
      wx.showToast({
        title: '分享图片生成中...',
        icon: 'loading',
        duration: 1000
      });
      //加载之后输出成图片
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'activityCanvas',
          success: function (res) {
            let canvasImgSrc = res.tempFilePath
            wx.setStorage({
              key: 'canvasImg',
              data: canvasImgSrc,
              success: function () {
                console.log("缓存成功")
              }
            })
            that.setData({
              canvas_src: res.tempFilePath
            });
            //triggerEvent:参数一为绑定组件的函数名，参数二为传递的数据。把生成的图片传递出去
            that.triggerEvent('openCanvas', { canvas_image_data: that.data.canvas_src })
            wx.hideToast()
          }
        }, that)
      }, 500)
    },
  },
})

/**
 * 绘制居中文本
 * ctx，字符串，x坐标，y坐标，宽，高，字符串最大长度
 * **/
function drawStrWithAlignCenter(ctx, str, x_, y_, width, height, max_length, scale) {
  // ctx.setTextAlign("center")
  //截取字符串宽度，初始高度,截取索引
  let lineWidth = 0;
  let initHeight = y_;
  let lastStrIndex = 0;
  let title_str = str.substring(0, max_length);
  console.log(title_str)
  // ctx.fillText("一二三四无六四吧就是", 0, initHeight, 315);
  for (let i = 0; i < title_str.length; i++) {
    lineWidth += (ctx.measureText(title_str[i]).width);
    if (lineWidth > width) {
      console.log("dayu")
      console.log(x_)
      ctx.fillText(title_str.substring(lastStrIndex, i), x_ + 6, initHeight, 315);//绘制截取部分。str,x,y
      initHeight += 25;//行高
      lastStrIndex = i;
    } else if (i == title_str.length - 1) {//绘制剩余部分
      ctx.fillText(title_str.substring(lastStrIndex, i + 1), ((width - lineWidth) / 2) + 6, initHeight);
    }
  }
}

/**
 * 绘制圆角矩形
 * canvas，X坐标，Y坐标，宽，高，圆角
 * **/
function drawRoundRect(cxt, x, y, width, height, radius) {
  cxt.beginPath();
  cxt.setFillStyle('transparent')
  cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
  cxt.lineTo(width - radius + x, y);
  cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
  cxt.lineTo(width + x, height + y - radius);
  cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);
  cxt.lineTo(radius + x, height + y);
  cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);
  cxt.closePath();
}